﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Practices.Unity;
using Ymatou.CommonService;
using Ymatou.PerfMonitorClient;
using YmatouSeller.Common.API;
using YmatouSeller.Notice.ApplicationService.Interface;
using YmatouSeller.NoticeAPI.Model.Request;
using YmatouSeller.NoticeAPI.Model.Response;
using System.IO;
using RestSharp;
using Ymatou.ServiceCenter;
using YmatouSeller.Notice.API.Models;
using YmatouSeller.Notice.Common;
using System.Text;

namespace YmatouSeller.Notice.API.Controllers
{
    public class NoticeManageController : BaseController
    {
        #region 运营后台用

        /// <summary>
        /// 消息通知单条详情
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ServiceRegister("api/NoticeManage/GetManageSystemNoticeItem", Method.GET)]
        [HttpGet]
        public BaseResponseModel<GetManageSystemNoticeItemResponse> GetManageSystemNoticeItem([FromUri]GetManageSystemNoticeItemRequest request)
        {
            using (MethodMonitor.New("api/NoticeManage/GetManageSystemNoticeItem"))
            {
                try
                {
                    ApplicationLog.Info(string.Format("api/NoticeManage/GetManageSystemNoticeItem请求Request：{0}", JsonConvert.SerializeObject(request)));
                    request.Validate();

                    var response = new GetManageSystemNoticeItemResponse();
                    response.SystemNoticeDetail = systemNoticeManageService.GetSystemNoticeItem(request.NoticeId);
                    if (response.SystemNoticeDetail != null)
                    {
                        if (response.SystemNoticeDetail.NoticeTarget == 1)
                        {
                            //用户ID查询用户名
                            var useLst = systemNoticeManageService.GetUserIDLstByLoginIds(response.SystemNoticeDetail.TargetList, 1);
                            response.SystemNoticeDetail.TargetDisList = useLst.Select(x => x.LoginID).Distinct().ToList();
                        }
                        else
                        {
                            response.SystemNoticeDetail.TargetDisList = response.SystemNoticeDetail.TargetList;
                        }
                    }
                    ApplicationLog.Info(string.Format("api/NoticeManage/GetManageSystemNoticeItem请求Response：{0}", JsonConvert.SerializeObject(response)));
                    return new SuccessResponseModel<GetManageSystemNoticeItemResponse>(response);
                }
                catch (Ymatou.API.Common.BussniessException ex)
                {
                    ApplicationLog.Info(string.Format("api/NoticeManage/GetManageSystemNoticeItem业务异常：Code={0},Msg={1}", ex.ErrorCode, ex.ErrorMsg));
                    return new BussniessErrorResponseModel<GetManageSystemNoticeItemResponse>(int.Parse(ex.ErrorCode), ex.ErrorMsg);
                }
                catch (Exception ex)
                {
                    ApplicationLog.Error("api/NoticeManage/GetManageSystemNoticeItem异常", ex);
                    return new SystemErrorResponseModel<GetManageSystemNoticeItemResponse>(ex.Message);
                }
            }
        }

        /// <summary>
        /// 通过洲名称查询国家
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ServiceRegister("api/NoticeManage/GetCountryList", Method.GET)]
        [HttpGet]
        public BaseResponseModel<GetCountryListResponse> GetCountryList([FromUri]GetCountryListRequest request)
        {
            using (MethodMonitor.New("api/NoticeManage/GetCountryList"))
            {
                try
                {
                    ApplicationLog.Info(string.Format("api/NoticeManage/GetCountryList请求Request：{0}", JsonConvert.SerializeObject(request)));
                    request.Validate();

                    var response = new GetCountryListResponse();
                    response.DataList = systemNoticeManageService.GetAllCountry(request.Continent, request.CountryID, request.SelectType);

                    ApplicationLog.Info(string.Format("api/NoticeManage/GetCountryList请求Response：{0}", JsonConvert.SerializeObject(response)));
                    return new SuccessResponseModel<GetCountryListResponse>(response);
                }
                catch (Ymatou.API.Common.BussniessException ex)
                {
                    ApplicationLog.Info(string.Format("api/NoticeManage/GetCountryList业务异常：Code={0},Msg={1}", ex.ErrorCode, ex.ErrorMsg));
                    return new BussniessErrorResponseModel<GetCountryListResponse>(int.Parse(ex.ErrorCode), ex.ErrorMsg);
                }
                catch (Exception ex)
                {
                    ApplicationLog.Error("api/NoticeManage/GetCountryList异常", ex);
                    return new SystemErrorResponseModel<GetCountryListResponse>(ex.Message);
                }
            }
        }

        /// <summary>
        /// 通过用户名批量查询用户名和ID
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ServiceRegister("api/NoticeManage/GetUserIDLstByLoginIds", Method.POST)]
        [HttpPost]
        public BaseResponseModel<GetUserIDLstByLoginIdsResponse> GetUserIDLstByLoginIds([FromBody]GetUserIDLstByLoginIdsRequest request)
        {
            using (MethodMonitor.New("api/NoticeManage/GetUserIDLstByLoginIds"))
            {
                try
                {
                    ApplicationLog.Info(string.Format("api/NoticeManage/GetUserIDLstByLoginIds请求Request：{0}", JsonConvert.SerializeObject(request)));
                    request.Validate();

                    var response = new GetUserIDLstByLoginIdsResponse();
                    var sellers = request.LoginIds;
                    response.DataList = systemNoticeManageService.GetUserIDLstByLoginIds(sellers, request.AccoutType);
                    if (response.DataList == null || response.DataList.Count <= 0)
                    {
                        response.Msg = "找不到买手：" + string.Join("，", sellers);
                    }
                    else if (response.DataList.Count < sellers.Count)
                    {
                        sellers = sellers.Where(x => !response.DataList.Select(o => o.LoginID.ToLower()).Contains(x.ToLower())).ToList();
                        response.Msg = "找不到买手：" + string.Join("，", sellers);
                    }

                    ApplicationLog.Info(string.Format("api/NoticeManage/GetUserIDLstByLoginIds请求Response：{0}", JsonConvert.SerializeObject(response)));
                    return new SuccessResponseModel<GetUserIDLstByLoginIdsResponse>(response);
                }
                catch (Ymatou.API.Common.BussniessException ex)
                {
                    ApplicationLog.Info(string.Format("api/NoticeManage/GetUserIDLstByLoginIds业务异常：Code={0},Msg={1}", ex.ErrorCode, ex.ErrorMsg));
                    return new BussniessErrorResponseModel<GetUserIDLstByLoginIdsResponse>(int.Parse(ex.ErrorCode), ex.ErrorMsg);
                }
                catch (Exception ex)
                {
                    ApplicationLog.Error("api/NoticeManage/GetUserIDLstByLoginIds异常", ex);
                    return new SystemErrorResponseModel<GetUserIDLstByLoginIdsResponse>(ex.Message);
                }
            }
        }

        /// <summary>
        /// 上传文件11
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ServiceRegister("api/NoticeManage/UploadFile", Method.POST)]
        [HttpPost]
        public BaseResponseModel<UploadFileResponse> UploadFile([FromBody]UploadFileRequest request)
        {
            using (MethodMonitor.New("api/NoticeManage/UploadFile"))
            {
                try
                {
                    ApplicationLog.Info(string.Format("api/NoticeManage/UploadFile请求Request：FileName={0}&UploadType={1}", request.FileName, request.UploadType));
                    request.Validate();

                    var response = new UploadFileResponse();

                    var ls = request.UploadData.Split(new string[] { "base64," }, StringSplitOptions.RemoveEmptyEntries);

                    byte[] imageBytes = Convert.FromBase64String(ls[ls.Length - 1]);

                    int length = imageBytes.Length;
                    int canUploadFileSize = AppSettingHelper.GetConfigValue<int>("CanUploadFileSize", 4);
                    //获取配置可上传的文件大小
                    int canUploadFileLength = 1024 * 1024 * canUploadFileSize;
                    if (length > canUploadFileLength)
                    {
                        throw new Ymatou.API.Common.BussniessException(string.Format("-1", "上传文件不能大于{0}M", canUploadFileSize));
                    }

                    response.FileUrl = systemNoticeManageService.UploadFile(imageBytes, request.FileName, request.UploadType);
                    if (!string.IsNullOrEmpty(response.FileUrl))
                    {
                        response.Status = true;
                    }
                    else
                    {
                        response.Msg = "上传失败";
                    }
                    ApplicationLog.Info(string.Format("api/NoticeManage/UploadFile请求Response：{0}", JsonConvert.SerializeObject(response)));
                    return new SuccessResponseModel<UploadFileResponse>(response);
                }
                catch (Ymatou.API.Common.BussniessException ex)
                {
                    ApplicationLog.Info(string.Format("api/NoticeManage/UploadFile业务异常：Code={0},Msg={1}", ex.ErrorCode, ex.ErrorMsg));
                    return new BussniessErrorResponseModel<UploadFileResponse>(int.Parse(ex.ErrorCode), ex.ErrorMsg);
                }
                catch (Exception ex)
                {
                    ApplicationLog.Error("api/NoticeManage/UploadFile异常", ex);
                    return new SystemErrorResponseModel<UploadFileResponse>(ex.Message);
                }
            }
        }

        /// <summary>
        /// 删除附件
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ServiceRegister("api/NoticeManage/DeleteNoticeAttachment", Method.POST)]
        [HttpPost]
        public BaseResponseModel<DeleteNoticeAttachmentResponse> DeleteNoticeAttachment([FromBody]DeleteNoticeAttachmentRequest request)
        {
            using (MethodMonitor.New("api/NoticeManage/DeleteNoticeAttachment"))
            {
                try
                {
                    ApplicationLog.Info(string.Format("api/NoticeManage/DeleteNoticeAttachment请求Request：{0}", JsonConvert.SerializeObject(request)));
                    request.Validate();

                    var response = new DeleteNoticeAttachmentResponse();
                    response.Status = systemNoticeManageService.DeleteNoticeAttachment(request.NoticeOptionIds, request.NoticeId);
                    if (response.Status)
                    {
                        response.Msg = "删除成功";
                    }
                    else
                    {
                        response.Msg = "删除失败";
                    }
                    ApplicationLog.Info(string.Format("api/NoticeManage/DeleteNoticeAttachment请求Response：{0}", JsonConvert.SerializeObject(response)));
                    return new SuccessResponseModel<DeleteNoticeAttachmentResponse>(response);
                }
                catch (Ymatou.API.Common.BussniessException ex)
                {
                    ApplicationLog.Info(string.Format("api/NoticeManage/DeleteNoticeAttachment业务异常：Code={0},Msg={1}", ex.ErrorCode, ex.ErrorMsg));
                    return new BussniessErrorResponseModel<DeleteNoticeAttachmentResponse>(int.Parse(ex.ErrorCode), ex.ErrorMsg);
                }
                catch (Exception ex)
                {
                    ApplicationLog.Error("api/NoticeManage/DeleteNoticeAttachment异常", ex);
                    return new SystemErrorResponseModel<DeleteNoticeAttachmentResponse>(ex.Message);
                }
            }
        }

        /// <summary>
        /// 新增消息通知
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ServiceRegister("api/NoticeManage/SaveSystemNotice", Method.POST)]
        [HttpPost]
        public BaseResponseModel<SaveSystemNoticeResponse> SaveSystemNotice([FromBody]SaveSystemNoticeRequest request)
        {
            using (MethodMonitor.New("api/NoticeManage/SaveSystemNotice"))
            {
                try
                {
                    ApplicationLog.Info(string.Format("api/NoticeManage/SaveSystemNotice请求Request：{0}", JsonConvert.SerializeObject(request)));
                    request.Validate();

                    var response = new SaveSystemNoticeResponse();
                    string msg = "";
                    response.Status = systemNoticeManageService.SaveSystemNotice(request.SystemNoticeDetail, ref msg);
                    if (response.Status)
                    {
                        response.Msg = "保存成功" + msg;
                    }
                    else
                    {
                        response.Msg = "保存失败" + msg;
                    }
                    ApplicationLog.Info(string.Format("api/NoticeManage/SaveSystemNotice请求Response：{0}", JsonConvert.SerializeObject(response)));
                    return new SuccessResponseModel<SaveSystemNoticeResponse>(response);
                }
                catch (Ymatou.API.Common.BussniessException ex)
                {
                    ApplicationLog.Info(string.Format("api/NoticeManage/SaveSystemNotice业务异常：Code={0},Msg={1}", ex.ErrorCode, ex.ErrorMsg));
                    return new BussniessErrorResponseModel<SaveSystemNoticeResponse>(int.Parse(ex.ErrorCode), ex.ErrorMsg);
                }
                catch (Exception ex)
                {
                    ApplicationLog.Error("api/NoticeManage/SaveSystemNotice异常", ex);
                    return new SystemErrorResponseModel<SaveSystemNoticeResponse>(ex.Message);
                }
            }
        }

        /// <summary>
        /// 消息通知列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ServiceRegister("api/NoticeManage/GetSystemNoticeList", Method.GET)]
        [HttpGet]
        public BaseResponseModel<GetSystemNoticeListResponse> GetSystemNoticeList([FromUri]GetSystemNoticeListRequest request)
        {
            using (MethodMonitor.New("api/NoticeManage/GetSystemNoticeList"))
            {
                try
                {
                    ApplicationLog.Info(string.Format("api/NoticeManage/GetSystemNoticeList请求Request：{0}", JsonConvert.SerializeObject(request)));
                    request.Validate();

                    var response = new GetSystemNoticeListResponse();
                    int totalCount = 0;
                    response.SystemNoticeList = systemNoticeManageService.GetSystemNoticeList(request.NoticeTitle, request.NoticeType, request.BeginTime, request.EndTime, request.PageIndex, request.PageSize, out totalCount);
                    response.TotalCount = totalCount;
                    ApplicationLog.Info(string.Format("api/NoticeManage/GetSystemNoticeList请求Response：{0}", JsonConvert.SerializeObject(response)));
                    return new SuccessResponseModel<GetSystemNoticeListResponse>(response);
                }
                catch (Ymatou.API.Common.BussniessException ex)
                {
                    ApplicationLog.Info(string.Format("api/NoticeManage/GetSystemNoticeList业务异常：Code={0},Msg={1}", ex.ErrorCode, ex.ErrorMsg));
                    return new BussniessErrorResponseModel<GetSystemNoticeListResponse>(int.Parse(ex.ErrorCode), ex.ErrorMsg);
                }
                catch (Exception ex)
                {
                    ApplicationLog.Error("api/NoticeManage/GetSystemNoticeList异常", ex);
                    return new SystemErrorResponseModel<GetSystemNoticeListResponse>(ex.Message);
                }
            }
        }

        #endregion

        #region 买手后台用

        /// <summary>
        /// 消息通知单条详情
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ServiceRegister("api/NoticeManage/GetSystemNoticeItem", Method.GET)]
        [HttpGet]
        public BaseResponseModel<GetSystemNoticeItemResponse> GetSystemNoticeItem([FromUri]GetSystemNoticeItemRequest request)
        {
            using (MethodMonitor.New("api/NoticeManage/GetSystemNoticeItem"))
            {
                try
                {
                    ApplicationLog.Info(string.Format("api/NoticeManage/GetSystemNoticeItem请求Request：{0}", JsonConvert.SerializeObject(request)));
                    request.Validate();

                    var response = new GetSystemNoticeItemResponse();
                    response.SystemNoticeDetail = systemNoticeManageService.GetSystemNoticeItem(request.NoticeId);
                    if (response.SystemNoticeDetail != null)
                    {
                        response.SystemNoticeDetail.AttachmentList.ForEach(p =>
                        {
                            if (p.OptionType == 2)
                            {
                                p.TransForFileUrl = string.Format("http://jsapi.sellerinfo.ymatou.com/FileDownload/Access?url={0}&filename={1}", System.Web.HttpUtility.UrlEncode(MyHelp.Encrypt(p.FileUrl, request.Sellerid.ToString())), System.Web.HttpUtility.UrlEncode(p.FileName));
                            }
                        });
                    }

                    ApplicationLog.Info(string.Format("api/NoticeManage/GetSystemNoticeItem请求Response：{0}", JsonConvert.SerializeObject(response)));
                    return new SuccessResponseModel<GetSystemNoticeItemResponse>(response);
                }
                catch (Ymatou.API.Common.BussniessException ex)
                {
                    ApplicationLog.Info(string.Format("api/NoticeManage/GetSystemNoticeItem业务异常：Code={0},Msg={1}", ex.ErrorCode, ex.ErrorMsg));
                    return new BussniessErrorResponseModel<GetSystemNoticeItemResponse>(int.Parse(ex.ErrorCode), ex.ErrorMsg);
                }
                catch (Exception ex)
                {
                    ApplicationLog.Error("api/NoticeManage/GetSystemNoticeItem异常", ex);
                    return new SystemErrorResponseModel<GetSystemNoticeItemResponse>(ex.Message);
                }
            }
        }

        /// <summary>
        /// 读通知操作
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ServiceRegister("api/NoticeManage/SaveSystemNotice", Method.POST)]
        [HttpPost]
        public BaseResponseModel<SubmitReadNoticeResponse> SubmitReadNotice([FromBody]SubmitReadNoticeRequest request)
        {
            using (MethodMonitor.New("api/NoticeManage/SaveSystemNotice"))
            {
                try
                {
                    ApplicationLog.Info(string.Format("api/NoticeManage/SubmitReadNotice请求Request：{0}", JsonConvert.SerializeObject(request)));
                    request.Validate();

                    var response = new SubmitReadNoticeResponse();
                    response.Success = systemNoticeManageService.SubmitReadNotice(request.SellerId, request.NoticeId,request.Resource);

                    ApplicationLog.Info(string.Format("api/NoticeManage/SubmitReadNotice请求Response：{0}", JsonConvert.SerializeObject(response)));
                    return new SuccessResponseModel<SubmitReadNoticeResponse>(response);
                }
                catch (Ymatou.API.Common.BussniessException ex)
                {
                    ApplicationLog.Info(string.Format("api/NoticeManage/SubmitReadNotice业务异常：Code={0},Msg={1}", ex.ErrorCode, ex.ErrorMsg));
                    return new BussniessErrorResponseModel<SubmitReadNoticeResponse>(int.Parse(ex.ErrorCode), ex.ErrorMsg);
                }
                catch (Exception ex)
                {
                    ApplicationLog.Error("api/NoticeManage/SubmitReadNotice异常", ex);
                    return new SystemErrorResponseModel<SubmitReadNoticeResponse>(ex.Message);
                }
            }
        }

        #endregion
    }
}